<!-- 角色分配用户弹窗内容 -->
<script setup lang="tsx">
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { useTable } from '@/hooks/web/useTable'
import { Table, TableColumn } from '@/components/Table'
// import { FormSchema } from '@/components/Form'
// import { Search } from '@/components/Search'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { ElTree, ElMessage } from 'element-plus'
import { getFirstNode } from '@/utils/tree'
import { sysOrgDataList, sysRoleQueryUserByRoleId, sysGrantBatchGrantUser } from '@/api/backstage'
import { SUCCESS_CODE } from '@/constants'

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})
const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const res = await sysRoleQueryUserByRoleId({
      orgId: unref(currentNodeKey), // 机构id
      roleId: unref(props.currentRow.id), // 角色id
      pageNum: 1,
      pageSize: 50000,
      ...unref(searchParams)
    })
    const list = res.data.records || []
    return {
      list: list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
// 接口暂不支持筛选
// const searchSchema = reactive<FormSchema[]>([
//   // {
//   //   field: 'username',
//   //   label: '用户账户',
//   //   component: 'Input'
//   // },
//   {
//     field: 'nickname',
//     label: '用户昵称',
//     component: 'Input'
//   },
//   {
//     field: 'mobile',
//     label: '手机号',
//     component: 'Input'
//   }
// ])
// const setSearchParams = async (params: any) => {
//   searchParams.value = params
//   await getList()
//   toggleSelection(unref(dataList.value))
// }

const multipleTableRef = ref<typeof Table>()
const toggleSelection = async (rows?: any[]) => {
  console.log('toggleSelection', rows)
  const elTableRef = await getElTableExpose()
  // elTableRef?.toggleAllSelection() // 全选
  if (rows) {
    const checkedRows = rows.filter((row) => row.owned)
    console.log('checkedRows', checkedRows)
    checkedRows.forEach((row) => {
      elTableRef?.toggleRowSelection(row, true)
    })
  }
}

const detailSchema = ref<DescriptionsSchema[]>([
  {
    field: 'name',
    label: '角色名称'
  },
  {
    field: 'roleType',
    label: '角色类型'
  }
])

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    label: '序号',
    type: 'selection'
  },
  {
    field: 'username',
    label: '用户名称'
  },
  {
    field: 'nickname',
    label: '用户昵称'
  },
  {
    field: 'mobile',
    label: '手机号'
  },
  { field: 'deptName', label: '所属部门' },
  {
    field: 'jobTitle',
    label: '职务岗位'
  }
])

const treeEl = ref<typeof ElTree>()
const currentNodeKey = ref('')
const departmentList = ref<any[]>([])
const ElTreeProp = {
  children: 'children',
  label: 'name',
  value: 'id'
}
const fetchDepartment = async () => {
  const res = await sysOrgDataList({})
  departmentList.value = res.data || []
  if (res.data.length === 0) return

  const nodeData: any = (res.data.length > 0 && getFirstNode(res.data)) || null
  currentNodeKey.value = nodeData.id || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  await getList()
  toggleSelection(unref(dataList.value))
}
const currentChange = async (data: any) => {
  currentNodeKey.value = data.id
  await getList()
  toggleSelection(unref(dataList.value))
}
fetchDepartment()

const submit = async () => {
  const elTableExpose = await getElTableExpose()
  const checkedKeys = elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  console.log('checkedKeys', checkedKeys)
  try {
    const res = await sysGrantBatchGrantUser({
      orgId: unref(currentNodeKey),
      roleId: props.currentRow?.id,
      users: checkedKeys
    })
    if (res.code === SUCCESS_CODE) {
      return true
    } else {
      ElMessage.error('保存失败')
      return false
    }
  } catch (error) {
    console.log(error)
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
const tablePageChange = async (page: number) => {
  console.log('tablePageChange', page)
  // currentPage.value = page
  await getList()
  toggleSelection(unref(dataList.value))
}
defineExpose({
  submit
})
</script>

<template>
  <Descriptions :schema="detailSchema" :data="currentRow || {}" />
  <div class="flex">
    <div class="w-1/5">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="ElTreeProp"
        @current-change="currentChange"
      />
    </div>
    <div class="flex-1">
      <!-- <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" /> -->
      <Table
        ref="multipleTableRef"
        :columns="tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
      />
    </div>
  </div>
</template>
